package qmm.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import qmm.entity.User;
import qmm.util.JdbcUtil;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public LoginServlet() {
        super();
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		String account = request.getParameter("account");
		String password = request.getParameter("password");
		String auto = request.getParameter("auto");
		try {
			Connection conn = JdbcUtil.getConnection();
			String sql = "select * from t_user where account='"+account+"' and password='"+password+"'";
			Statement st = conn.createStatement();
			ResultSet rs = st.executeQuery(sql);
			if(rs.next()){
				if("on".equals(auto)){
					Cookie cookie1 = new Cookie("account",account);
					Cookie cookie2 = new Cookie("password",password);
					response.addCookie(cookie1);
					response.addCookie(cookie2);
				}
				int id = rs.getInt("id");
				String account2 = rs.getString("account");
				String nickname = rs.getString("nick_name");
				String password2 = rs.getString("password");
				int gender = rs.getInt("gender");
				String idCardNo = rs.getString("id_card_no");
				String email = rs.getString("email");
				String phone = rs.getString("phone");
				int type = rs.getInt("type");
				String face = rs.getString("face");
				User user = new User(id, account2, nickname, password2, gender, idCardNo, email, phone, type,face);
				System.out.println(user.toString());
				session.setAttribute("user", user);
				session.removeAttribute("msg");
				response.sendRedirect("index.jsp");
			}else{
				System.out.println("用户名或密码错误");
				session.setAttribute("msg", "用户名或密码错误");
				response.sendRedirect("login.jsp");
			}
		}catch (SQLException e) {
			e.printStackTrace();
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
